document.addEventListener('DOMContentLoaded', function() {
    const dropZone = document.getElementById('drop-zone');
    const fileInput = document.getElementById('file-input');
    const uploadBtn = document.getElementById('upload-btn');
    const previewContainer = document.getElementById('preview-container');
    const originalImg = document.getElementById('original-img');
    const resultImg = document.getElementById('result-img');
    const processBtn = document.getElementById('process-btn');
    const downloadBtn = document.getElementById('download-btn');
    const resetBtn = document.getElementById('reset-btn');

    // API配置
    const API_KEY = 'fgMyWno9U56ix2jPmX5zMrV4';
    const API_URL = 'https://api.remove.bg/v1.0/removebg';

    // 处理拖放
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, preventDefaults, false);
        document.body.addEventListener(eventName, preventDefaults, false);
    });

    // 添加拖放视觉反馈
    ['dragenter', 'dragover'].forEach(eventName => {
        dropZone.addEventListener(eventName, highlight, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, unhighlight, false);
    });

    // 处理文件拖放
    dropZone.addEventListener('drop', handleDrop, false);

    // 处理文件选择
    uploadBtn.addEventListener('click', () => fileInput.click());
    fileInput.addEventListener('change', handleFileSelect);

    // 处理按钮点击
    processBtn.addEventListener('click', processImage);
    downloadBtn.addEventListener('click', downloadResult);
    resetBtn.addEventListener('click', resetUpload);

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    function highlight(e) {
        dropZone.classList.add('dragover');
    }

    function unhighlight(e) {
        dropZone.classList.remove('dragover');
    }

    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        handleFiles(files);
    }

    function handleFileSelect(e) {
        const files = e.target.files;
        handleFiles(files);
    }

    function handleFiles(files) {
        if (files.length > 0) {
            const file = files[0];
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    originalImg.src = e.target.result;
                    previewContainer.classList.remove('hidden');
                    dropZone.classList.add('hidden');
                    resultImg.src = ''; // 清空结果图片
                    downloadBtn.disabled = true;
                };
                reader.readAsDataURL(file);
            } else {
                alert('请上传图片文件！');
            }
        }
    }

    async function processImage() {
        try {
            processBtn.disabled = true;
            processBtn.textContent = '处理中...';

            // 获取当前显示的图片文件
            const imageFile = await fetch(originalImg.src)
                .then(res => res.blob())
                .then(blob => new File([blob], 'image.jpg', { type: 'image/jpeg' }));

            // 创建FormData对象
            const formData = new FormData();
            formData.append('image_file', imageFile);
            formData.append('size', 'auto');

            // 调用remove.bg API
            const response = await fetch(API_URL, {
                method: 'POST',
                headers: {
                    'X-Api-Key': API_KEY
                },
                body: formData
            });

            if (!response.ok) {
                throw new Error('API请求失败');
            }

            // 获取返回的图片数据
            const blob = await response.blob();
            const imageUrl = URL.createObjectURL(blob);
            resultImg.src = imageUrl;
            
            downloadBtn.disabled = false;
            processBtn.textContent = '开始处理';
            processBtn.disabled = false;
        } catch (error) {
            console.error('处理图片时出错：', error);
            alert('处理图片时出错，请重试！');
            processBtn.textContent = '开始处理';
            processBtn.disabled = false;
        }
    }

    function downloadResult() {
        const link = document.createElement('a');
        link.download = 'no-background.png';
        link.href = resultImg.src;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    function resetUpload() {
        previewContainer.classList.add('hidden');
        dropZone.classList.remove('hidden');
        originalImg.src = '';
        resultImg.src = '';
        fileInput.value = '';
        downloadBtn.disabled = true;
    }
});
